﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using BrainTechLLC;
using BrainTechLLC.ThreadSafeObjects;

namespace UserInterface
{
	public partial class MapVisualizer : UserControl
	{
		protected List<LocationInt> _visited;
		protected SparseArrayCustom<GameLocation> _world;
		public SparseArrayCustom<GameLocation> World
		{
			get { return _world; }
			set { _world = value; }
		}

		public void UpdateDisplay()
		{
			panelMap.Controls.Clear();
			GameLocation loc = _world[0, 0, 1];
			_visited = new List<LocationInt>();
			BuildMapRecursive(loc, 0, 0, GeneralDirection.None);
		}

		public void BuildMapRecursive(GameLocation loc, int x, int y, GeneralDirection cameFrom)
		{
			if (loc == null)
				return;

			LocationInt l = _visited.Find((v1) => v1 == loc.XYZ);

			if (l != null)
				return;

			_visited.Add(loc.XYZ);

			MapLocation mapLocation = new MapLocation()
			{
				GameLocation = loc,
				Left = x,
				Top = y,
				Width = 64,
				Height = 64
			};

			panelMap.Controls.Add(mapLocation);
			LocationEdge w = loc.Edges[(int)GeneralDirection.W];
			LocationEdge e = loc.Edges[(int)GeneralDirection.E];
			LocationEdge n = loc.Edges[(int)GeneralDirection.N];
			LocationEdge s = loc.Edges[(int)GeneralDirection.S];
			if (w != null && cameFrom != GeneralDirection.W && w.ToGameLocation != null)
			{
				BuildMapRecursive(w.ToGameLocation, x - 64, y, GeneralDirection.E);
			}
			if (e != null && cameFrom != GeneralDirection.E && e.ToGameLocation != null)
			{
				BuildMapRecursive(e.ToGameLocation, x + 64, y, GeneralDirection.W);
			}
			if (n != null && cameFrom != GeneralDirection.N && n.ToGameLocation != null)
			{
				BuildMapRecursive(n.ToGameLocation, x, y - 64, GeneralDirection.S);
			}
			if (s != null && cameFrom != GeneralDirection.S && s.ToGameLocation != null)
			{
				BuildMapRecursive(s.ToGameLocation, x, y + 64, GeneralDirection.N);
			}
		}

		public MapVisualizer()
		{
			InitializeComponent();
		}

		private void MapVisualizer_Load(object sender, EventArgs e)
		{
			UpdateDisplay();
		}
	}
}
